package com.example.k12.utlis

import android.content.Context
import com.bumptech.glide.load.Transformation
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.BitmapShader
import android.graphics.Shader
import com.bumptech.glide.load.engine.Resource
import com.bumptech.glide.load.resource.bitmap.BitmapResource
import java.security.MessageDigest

class CircleTransform : Transformation<Bitmap> {
    override fun transform(
        context: Context,
        resource: Resource<Bitmap>,
        outWidth: Int,
        outHeight: Int
    ): Resource<Bitmap> {
        val bitmap = resource.get()
        val size = minOf(bitmap.width, bitmap.height)
        val x = (bitmap.width - size) / 2
        val y = (bitmap.height - size) / 2

        val squared = Bitmap.createBitmap(bitmap, x, y, size, size)
        val bitmapPool = com.bumptech.glide.Glide.get(context).bitmapPool
        val result = bitmapPool.get(size, size, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        val paint = Paint()
        val shader = BitmapShader(squared, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        paint.shader = shader
        paint.isAntiAlias = true

        val radius = size / 2f
        canvas.drawCircle(radius, radius, radius, paint)

        bitmapPool.put(squared) // 回收临时bitmap

        return BitmapResource.obtain(result, bitmapPool)!!
    }

    override fun equals(other: Any?): Boolean = other is CircleTransform

    override fun hashCode(): Int = javaClass.hashCode()

    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
        messageDigest.update(javaClass.simpleName.toByteArray())
    }
}

